<template>
	<view class="content">
		<view class="status_bar">
			<!-- 这里是状态栏 -->
		</view>
		<view style="width: 100%;display: flex;justify-content: space-between;align-items: center;padding: 0 16rpx;box-sizing: border-box;">
			<view style="box-sizing: border-box;" @click="goBack">
				<view style="border: 2rpx solid #E5E6E8;border-radius: 24rpx;background-color: #FFF;">
					<image style="width: 36rpx;height: 36rpx;margin: 16rpx 16rpx 4rpx;" src="/static/images/icon/left-icon.png"></image>
				</view>
			</view>
			<view style="color: #232426;font-size: 32rpx;font-weight: 500;padding-left: 80rpx;">
				{{typeTitle}}
			</view>
			<view @click="submit" style="color: #1AAEC0;font-size: 28rpx;font-weight:400;border-radius: 200rpx;border: 2rpx solid #1AAEC0;padding: 14rpx 42rpx;">
				發佈
			</view>
		</view>
		<view style="margin-top: 28rpx; width: 100%;box-sizing: border-box;padding: 0 30rpx;">
			<view style="background-color: #FFF;border-radius: 40rpx;">
				<view style="display:flex; overflow-x: auto; padding: 24rpx;gap: 12rpx; width: 90%; ">
					<view v-for="(item, index) in images" :key="index"  style="width: 180rpx;height: 210rpx;background-color: #F0F0F0;border-radius: 20rpx;flex-shrink: 0;">
						<view style="position: relative;display: inline-block;" @click="showImgFn(index)">
							<u-image
								:src="item.url"
								width="180rpx"
								height="210rpx"
								radius="20rpx"
							></u-image>
							<view v-if="index == 0" style="position: absolute;bottom:8rpx;left:8rpx;color: #fff;font-size: 22rpx;border-radius: 20rpx;padding: 8rpx 20rpx;background-color: rgba(0, 0, 0, 0.4)">
								封面
							</view>
						</view>
					</view>
					<view style="width: 180rpx;height: 210rpx;background-color: #F0F0F0;border-radius: 20rpx;flex-shrink: 0;" @click="chooseImg" v-if="images.length < 6">
						<view style="margin: 87rpx 0 0 72rpx;">
							<u-image
								src="/static/images/icon/plus-grey.png"
								width="36rpx"
								height="36rpx"
							></u-image>
						</view>
					</view>
				</view>
				<view style="border-top: 2rpx solid #FAFAFA;padding:28rpx 24rpx 0;">
					<u-input name="title" placeholder="請輸入標題,獲得更多瀏覽量" v-model="form.title" border="none" maxlength="20" @change="handleInput"></u-input>
					<view style="color:#BEC0C5;font-size: 20rpx;display: flex;justify-content: flex-end;">
						{{input_count}} / 20
					</view>
				</view>
				<view style="border-top: 2rpx solid #FAFAFA;padding:28rpx 24rpx 0;">
					<!-- <u-textarea 
						v-model="form.introduce" 
						placeholder="請輸入介紹文字，有趣的詳細內容可加分！" 
						border="none"  
						maxlength="500" 
						height="240" 
						@change="handleTextarea" 
						:confirmType="null" 
						ref="myTextarea"
						:focus="isFocus" 
						></u-textarea> -->
						<editor 
							id="editor" 
							placeholder="請輸入介紹文字，有趣的詳細內容可加分！"
							@input="onInput"
							@ready="onEditorReady" 
						>
						</editor>
				</view>
				<view style="border-top: 2rpx solid #FAFAFA;padding:28rpx 24rpx;display: flex;justify-content: space-between;">
					<view style="display: flex;justify-content: flex-start;">
						<view @click="openNicknameFn">
							<u-image
								src="/static/images/icon/at.png"
								width="40rpx"
								height="40rpx"
							></u-image>
						</view>
						<view style="margin-left: 38rpx;"  @click="openTopicFn">
							<u-image
								src="/static/images/icon/well-no.png"
								width="40rpx"
								height="40rpx"
							></u-image>
						</view>
					</view>
					<view style="color:#BEC0C5;font-size: 20rpx;">
						{{textarea_count}} / 500
					</view>
				</view>
			</view>
		</view>
		
		<view style="margin-top: 24rpx; width: 100%;box-sizing: border-box;padding: 0 30rpx;">
			<view class="list-item" @click="openClassifyFn">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">分類</view>
						<view class="warning-bag">*</view>
					</view>
					<view :class="{'item-subtitle':classifyCheck==false,'item-subtitle-active':classifyCheck==true}" >
						{{form.classify}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
		</view>
		
		<view style="margin-top: 24rpx; width: 100%;box-sizing: border-box;padding: 0 30rpx;">
			<view v-if="typeItem != 3" class="list-item" @click="openTypeFn">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">預約類型</view>
						<view class="warning-bag">*</view>
					</view>
					<view :class="{'item-subtitle':typeNameCheck==false,'item-subtitle-active':typeNameCheck==true}" >
						{{typeName}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			<view v-if="this.form.type == 1" @click="openAreaFn" class="list-item" >
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">服務地址</view>
						<view class="warning-bag">*</view>
					</view>
					<view class="item-subtitle" >
						{{areaName}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			<view v-if="this.form.type == 2 || this.typeItem == 3" @click="openAddressFn" class="list-item">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">{{ typeItem == 3?'地點':'服務地址' }} </view>
						<view class="warning-bag">*</view>
					</view>
					<view class="item-subtitle" >
						{{ city_address }}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			<view v-if="typeItem != 3" class="list-item" @click="openMeterFn">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">收費計價</view>
						<view class="warning-bag">*</view>
					</view>
					<view class="item-subtitle">
						{{priceName}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
			<view v-if="typeItem != 3" class="list-item" @click="openAppointmentFn">
				<view class="list-item-title">
					<view class="item-title">
						<view class="title">預約時間</view>
						<view class="warning-bag">*</view>
					</view>
					<view class="item-subtitle" >
						{{appointmentStr}}
					</view>
				</view>
				<view>
					<u-image
						src="/static/images/icon/right-icon.png"
						width="40rpx"
						height="40rpx"
					></u-image>
				</view>
			</view>
		</view>
		
		<!--圖片查看開始-->
		<u-overlay :show="showImg" opacity="1" :duration="400">
			<view class="container">
				<view class="imgs">
					<image
						:src="picUrl"
						mode="widthFix"
						style="width: 100%;"
					></image>
				</view>
				<view class="footer">
					<view class="btn" @click="delImg">刪除</view>
					<view class="btn" @click="endShowImg">完成</view>
				</view>
			</view>
		</u-overlay>
		<!--圖片查看結束-->
		
		<!--好友搜索-->
		<u-popup :show="showUserPopup" @close="showUserPopup = false" :round="60">
			<view class="user-search-popup">
				<view>
					<u-search 
						placeholder="搜尋"
						:focus="searchUserFocus"
						v-model="keyword" 
						@change="changeNameSearch"
					></u-search>
				</view>
				<view>
					<view v-for="(item, index) in userList" :key="index" class="search-popup-item" @click="checkNickname(index)">
						<view>
							<u--image
								:src="item.url"
								shape="circle"
								width="56rpx"
								height="56rpx"
							></u--image>
						</view>
						<view class="title">
							<text v-for="(segment, index_) in item.highlightTitle" :key="index_" :class="{ 'highlight': segment.highlight }">
								{{segment.text}}
							</text>
						</view>
					</view>
					<view v-if="userList.length == 0" style="width: 100%;color: rgb(131, 133, 138);align-items: center;height: 500rpx;display: flex;justify-content: center;">
						没有找到符合条件的用户
					</view>
				</view>
			</view>
		</u-popup>
		<!--好友搜索結束-->
		
		<!--話題搜索-->
		<u-popup :show="showTopicPopup" @close="showTopicPopup = false" :round="60">
			<view class="user-search-popup">
				<view>
					<u-search
						placeholder="搜尋"
						:focus="searchTopicFocus"
						v-model="keyword" 
						@change="changeTopicSearch"
					></u-search>
				</view>
				<view>
					<view v-for="(item, index) in topicList" :key="index" class="search-popup-item" @click="checkTopic(index)">
						<view>
							<u--image
								src="/static/images/icon/topic.png"
								shape="circle"
								width="56rpx"
								height="56rpx"
							></u--image>
						</view>
						<view class="title">
							<text v-for="(segment, index_) in item.highlightTitle" :key="index_" :class="{ 'highlight': segment.highlight }">
								{{segment.text}}
							</text>
						</view>
					</view>
					<view v-if="topicList.length == 0" style="width: 100%;color: rgb(131, 133, 138);">
						<view style="width: 100%;text-align: center;margin-top: 150rpx;">没有找到符合条件的结果</view>
						<view v-if="keyword.length > 0" style="width: 100%;margin-top: 40rpx;">
							<view style="border:2rpx solid #BEC0C5;width: 220rpx;margin: 0 auto;text-align: center;padding: 8rpx 20rpx;font-size: 28rpx;border-radius: 200rpx;" @click="addTags">創建成新話題</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!--話題搜索結束-->
		
		<!--預約類型-->
		<u-popup :show="showType" mode="bottom" round="48rpx" @close="showType=false">
			<view class="popup-push-type">
				<view class="popup-push-header">
					<view class="site" @click="closeTypeFn">取消</view>
					<view class="site title">預約類型</view>
					<view class="site btn" @click="setTypeFn">選擇</view>
				</view>
				<view class="popup-push-body">
					<view class="popup-push-list">
						
						<view class="popup-push-item" v-for="(item,index) in typeList" :key="index" @click="checkTypeFn(item.type)">
							<view class="popup-push-icon">
								<u-image
									v-if="item.type == typeId"
									src="/static/images/icon/success-solid.png"
									width="48rpx"
									height="48rpx"
								></u-image>
								<view v-else class="popup-push-radio"></view>
							</view>
							<view class="popup-push-text">
								<view class="title">{{item.title}}</view>
								<view class="describe">{{item.describe}}</view>
							</view>
						</view>
						
					</view>
				</view>
			</view>
		</u-popup>
		<!--預約類型結束-->
		
	</view>
</template>

<script>
	import { archivesPost, tagsSearch, userSearch, tagsAdd } from '@/config/api.js';
	
	export default {
		data() {
			return {
				typeItem:1,
				typeTitle:'發佈任務需求',
				form:{
					type:0,
					title:'',
					introduce:'',
					classify:'選擇分類',
					channel_address:'',
					channel_map:''
				},
				classifyCheck:false,
				images:[],
				input_count:0,
				textarea_count:0,
				showImg:false,
				picUrl:'',
				current:-1,
				keyword:'',
				tagsWord:'',
				showUserPopup:false,
				userList:[],//查詢結果
				userIds:[],//存放用戶@結果
				isFocus:false,
				showTopicPopup:false,
				topicList:[],
				isTopicFocus:false,
				sign:'',
				showType:false,
				typeId:0,
				typeNameCheck:false,
				typeName:'選擇類型',
				typeList:[],
				typeList_expert:[{
					type:1,
					title:'到府',
					describe:'可至指定地點提供服務'
				},
				{
					type:2,
					title:'到店',
					describe:'您有店面，可讓顧客預約並前往體驗'
				},
				{
					type:3,
					title:'線上',
					describe:'無距離限制，彈性提供專業服務'
				}],
				typeList_task:[{
					type:2,
					title:'指定地點',
					describe:'需讓達人至指定地點提供服務，您需提供地址'
				},
				{
					type:3,
					title:'線上',
					describe:'無距離限制，彈性提供專業服務'
				}],
				areaIds:'',//選擇的城市id集合
				areaName:'選擇區域',
				priceName:'選擇價錢',
				price:0,
				unitValue:'次',
				editorCtx: null,
				searchUserTimeout:null,
				searchTopicTimeout:null,
				searchUserFocus:false,
				searchTopicFocus:false,
				appointmentList:[[],[],[],[],[],[],[]],
				appointmentStr:"選擇時間",
				nums:0,
				city_address:this.typeItem == 3?'選擇你要分享的地點':'服務地址'
			}
		},
		onLoad(option) {
			if( option.type == 'expert' ){
				this.typeTitle = '發佈達人技能';
				this.typeList = this.typeList_expert;
				this.typeItem = 1;
			} else if(option.type == 'task'){
				this.typeTitle = '發佈任務需求';
				this.typeList = this.typeList_task;
				this.typeItem = 2;
			} else if(option.type == 'colony'){
				this.typeTitle = '發佈貼文';
				this.typeItem = 3;
			} else {
				
			}
			console.log('type', this.typeItem)
		},
		mounted(){
			this.$nextTick(() => {
				this.searchUserFocus = true
			})
		},
		methods: {
			//标题字数统计
			handleInput(){
				this.input_count = this.form.title.replace(/[\s\n]/g, '').length;
			},
			//初始化富文本框
			onEditorReady() {
				uni.createSelectorQuery()
				.select('#editor')
				.context(res => {
					this.editorCtx = res.context
				}).exec()
			},
			//监听富文本
			onInput(e) {
				this.form.introduce = e.detail.html
				//統計字數
				this.textarea_count = e.detail.text.length;
				
				//監聽@或者#输入
				let cleanString = this.form.introduce
					.replace(/<[^>]+>/g, '')
					.replace(/[\s\n]/g, '');
				const lastChar = cleanString.slice(-1);
				
				
				// 判断是否为@或#
				if (lastChar === '@') {
					this.sign = '@';
					this.showUserPopup = true;//输入框@形式触发，添加内容不需要再添加@符号
				} else if(lastChar === '#'){
					this.sign = '#';
					this.showTopicPopup = true;
				} else {
					this.showUserPopup  = false;
					this.showTopicPopup = false;
				}
			},
			//监听textarea(弃用)
			handleTextarea(){
				//統計字數
				this.textarea_count = this.form.introduce.replace(/[\s\n]/g, '').length;
				//監聽
				const lastChar = this.form.introduce.slice(-1);
				// 判断是否为@或#
				if (lastChar === '@') {
					this.openNicknameFn();
					this.sign = '';
				} else if(lastChar === '#'){
					this.openTopicFn();
					this.sign = '';
				} else {
					this.showUserPopup  = false;
					this.showTopicPopup = false;
				}
				// const lastAtIndex = content.lastIndexOf('@');
				// if (lastAtIndex === -1) {
				// 	console.log('關閉彈窗'); // 无@则关闭弹窗
				// 	return;
				// }
				// // 提取@后的内容（直到遇到空格或结尾）
				// const keyword = content.slice(lastAtIndex + 1).split(/\s/)[0];
				// console.log('搜索內容:', keyword);
				// console.log('打開彈窗'); // 打开弹窗
			},
			//使用点击打开@
			openNicknameFn(){
				this.userList = [];
				this.showUserPopup = true;
			},
			//使用点击打开#
			openTopicFn(){
				this.topicList = [];
				this.showTopicPopup = true;
			},
			changeNameSearch(){
				let that = this;
				that.userList = [];
				if(that.keyword.length == 0)return;
				uni.showLoading();
				clearTimeout(this.searchUserTimeout);
				this.searchUserTimeout = setTimeout(()=>{
					let data = {
						keyword:that.keyword
					}
					userSearch(data).then((res) => {
						for( let o in res ){
							that.userList.push({
								id:res[o].id,
								url:res[o].avatar,
								title:res[o].nickname,
								highlightTitle:[]
							})
						}
						that.setHighlightTitle(that.userList)
						uni.hideLoading()
						
					}).catch((e) =>{
						console.log('error', e)
					})
				}, 500);
			},
			checkNickname(id){
				let that = this;
				let str  = '';
				if(this.sign == ''){
					str = that.form.introduce + `<a href="/pages/home/user?id=${that.userList[id].id}" style="color:#337F89;text-decoration: none;">${that.userList[id].title}&nbsp;</a>`
				} else {
					//在符号处
					str = that.processRichText(that.form.introduce, '@', that.userList[id].id, that.userList[id].title)
					// str = that.form.introduce + `<a href="/pages/home/user?id=${that.userList[id].id}" style="color:#337F89;text-decoration: none;">$1${that.userList[id].title}&nbsp;</a>`
				}
				that.userIds.push(that.userList[id].id);
				that.sign = '';
				that.keyword = '';
				that.form.introduce = str;
				that.showUserPopup = false;
				uni.createSelectorQuery()
					.in(this)
					.select('#editor')
					.context(res => {
						this.editorCtx = res.context
						// 初始化赋值
						this.editorCtx.setContents({
							html: str,
							success:()=>{
								// this.editorCtx.setSelectionRange({
								// 	start: str.length,
								// 	end: str.length
								// })
							}
						})
						
						// const delta = {
						//     ops: [{
						//       insert: that.userList[id].title,
						//       attributes: { color: '#188CA2' }
						//     }]
						// };
						//方案一：insertContents
						// this.editorCtx.insertContents(delta);
						
						//兼容性方案：setContents
						// const newOps = res.ops.concat(delta.ops);
						// this.editorCtx.setContents({ ops: newOps });
						
					}).exec()
			},
			changeTopicSearch(){
				let that = this;
				that.topicList = [];
				if(that.keyword.length == 0)return;
				uni.showLoading();
				clearTimeout(this.searchTopicTimeout);
				this.searchTopicTimeout = setTimeout(()=>{
					let data = {
						keyword:that.keyword
					}
					tagsSearch(data).then((res) => {
						console.log('sucess', res)
						for( let o in res ){
							that.topicList.push({
								id:res[o].id,
								title:res[o].title,
								highlightTitle:[]
							})
						}
						that.setHighlightTitle(that.topicList)
						uni.hideLoading()
						
					}).catch((e) =>{
						console.log('error', e)
					})
				}, 500);
			},
			checkTopic(key){
				let id = this.topicList[key].id;
				let title = this.topicList[key].title;
				this.insertTags(id, title);
			},
			insertTags(id,title){
				let that = this;
				let str = '';
				if(this.sign == ''){
					str = that.form.introduce + `<a href="/pages/home/topic?id=${id}" style="color:#337F89;text-decoration: none;">${title}&nbsp;</a>`
				} else {
					//在符号处
					str = that.processRichText(that.form.introduce, '#', id, title)
				}
				console.log(str)
				// that.processRichText(that.form.introduce, '#', that.topicList[id].title)
				that.sign    = '';
				that.keyword = '';
				that.form.introduce = str;
				that.showTopicPopup = false;
				uni.createSelectorQuery()
					.in(this)
					.select('#editor')
					.context(res => {
						this.editorCtx = res.context
						// 初始化赋值
						this.editorCtx.setContents({
							html: str,
							success:()=>{
								
							}
						})
						
					}).exec()
			},
			setHighlightTitle(data){
				for( let i in data ){
					console.log(data[i].title)
					data[i].highlightTitle = this.highlightTitle(data[i].title);
				}
			},
			//高亮搜索結果
			highlightTitle(title){
				if (!this.keyword) {
					// 无关键词时显示完整标题
				    return [{ text: title, highlight: false }];
				}
				
				const segments = [];
				let remainingText = title;
				const lowerKeyword = this.keyword; // 不区分大小写
				
				// 循环切割匹配部分
				while (remainingText) {
					const lowerText = remainingText;
					const index = lowerText.indexOf(lowerKeyword);
			
					if (index === -1) {
						segments.push({ text: remainingText, highlight: false });
						break;
					}
			
					// 切割非匹配部分
					if (index > 0) {
						segments.push({
							text: remainingText.slice(0, index),
							highlight: false
						});
					}
			
					// 切割匹配部分
					segments.push({
						text: remainingText.slice(index, index + this.keyword.length),
						highlight: true
					});
			
					// 剩余文本继续处理
					remainingText = remainingText.slice(index + this.keyword.length);
				}
				return segments;
			},
			//在符号处插入
			processRichText(content, symbol, id, title) {
				const color = "#337F89";
				const pattern = new RegExp(`(${symbol})`);
				if(symbol == '@'){
					return content.replace(pattern, `<a href="/pages/home/user?id=${id}" style="color:#337F89;text-decoration: none;">${title}&nbsp;</a>`);
				} else {
					return content.replace(pattern, `<a href="/pages/home/topic?id=${id}" style="color:#337F89;text-decoration: none;">${title}&nbsp;</a>`);
				}
			},
			goBack(){
				uni.navigateBack();
			},
			chooseImg(){
				let that = this;
				let uploadUrl = uni.$u.http.config.baseURL+'/api/home/upload'
				uni.chooseImage({
					count:6,
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						console.log(tempFilePaths)
						for(let i=0;i<tempFilePaths.length;i++){
							uni.uploadFile({
								url: uploadUrl,
								header: {
								    'Authorization': 'Bearer ' + uni.getStorageSync('token')// 从全局获取token
								  },
								filePath: tempFilePaths[i],
								name: 'file',
								formData: {
									'type': 'cms',
									'timestamp': Date.now()
								},
								success: (uploadFileRes) => {
									// that.images.push({url:tempFilePaths[i]});
									console.log(uploadFileRes)
									let res = JSON.parse(uploadFileRes.data)
									that.images.push({url:res.fullurl});
									console.log(that.images)
								}
							});
						}
					},
					fail:(e)=>{
						console.log('error', e)
					},
					complete:(res)=>{
						console.log('complete', res)
					}
				});
			},
			showImgFn(e){
				console.log(this.images[e].url)
				this.picUrl = this.images[e].url;
				this.current = e;
				this.showImg = true;
			},
			endShowImg(){
				this.picUrl = '';
				this.current = -1;
				this.showImg = false;
			},
			delImg(){
				this.images.splice(this.current, 1);
				this.endShowImg();
			},
			//从文本中，提取所有@或者#内容，并返回数组
			extractMentions(htmlStr, symbol = '@') {
			    // 处理HTML空格符和换行符^^5]^3^^
			    const normalizedStr = htmlStr
			        .replace(/&nbsp;/g, ' ')
			        .replace(/\n/g, ' ');
			      
			    // 构建动态正则表达式^^7]^4^^
			    const regex = new RegExp(`${symbol}[^\\s<]+`, 'g');
			    return normalizedStr.match(regex) || [];
			},
			//選擇分類
			openClassifyFn(){
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/filter',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data);
							that.form.classify = data.data[0].title;
							that.classifyCheck = true;
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						res.eventChannel.emit('initData', { maxCount: 1 });
					}
				});
			},
			openTypeFn(){
				this.typeId = this.form.type;
				this.showType = true;
			},
			closeTypeFn(){
				this.typeId = 0;
				this.showType = false;
			},
			checkTypeFn(type){
				this.typeId = type;
			},
			setTypeFn(){
				this.form.type = this.typeId;
				for(let i in this.typeList){
					if( this.typeList[i].type == this.form.type ){
						this.typeName = this.typeList[i].title;
						this.typeNameCheck = true;
					}
				}
				if( this.typeId == 3 ){
					//綫上，默認發全臺北
					let citys = [];
					for( let i=43;i<=65;i++ ){
						citys.push(i);
					}
					this.areaIds = citys.join(',');
				}
				this.closeTypeFn();
			},
			addTags(){
				let that = this;
				let parames = {
					title:this.keyword
				}
				tagsAdd(parames).then((res) => {
					console.log('sucess', res)
					//success
					//添加到對話框
					that.insertTags(res,that.keyword);
				}).catch((e) =>{
					console.log('error', e)
				})
			},
			//城市選擇
			openAreaFn(){
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/city?type='+this.typeItem,
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data);
							that.areaIds = data.city.join(',');
							that.areaName = data.name.join(',');
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						// res.eventChannel.emit('initData', { type: 1 });
					}
				});
			},
			//地址選擇（到店）
			openAddressFn(){
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/address',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data.data);
							that.city_address = data.data.cityName+data.data.street+data.data.room
							that.form.channel_address = that.city_address;
							that.form.channel_map = data.data.longitude + ','+data.data.latitude;
							//地址選擇城市id判斷
							if( data.data.countryId == 1 ){
								//台灣地區
								let citys = [];
								for( let i=43;i<=65;i++ ){
									citys.push(i);
								}
								that.areaIds = citys.join(',');
							} else if(data.data.countryId == 2){
								let citys = [];
								for( let i=66;i<=78;i++ ){
									citys.push(i);
								}
								that.areaIds = citys.join(',');
							} else if(data.data.countryId == 3){
								that.areaIds = 41;
							} else if(data.data.countryId == 4){
								that.areaIds = 42;
							} else {
								let citys = [];
								for( let i=41;i<=78;i++ ){
									citys.push(i);
								}
								that.areaIds = citys.join(',');
							}
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						// res.eventChannel.emit('initData', { type: 1 });
					}
				});
			},
			//打開價格設置
			openMeterFn(){
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/meter',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('接收数据:', data);
							that.priceName =  'NT $' + data.price + '/'+ data.unit;
							that.price = data.price;
							that.unitValue = data.unitValue
							that.nums = data.nums
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						// res.eventChannel.emit('initData', { type: 1 });
					}
				});
			},
			//打開時間設置
			openAppointmentFn(){
				let that = this;
				uni.navigateTo({
					url: '/pages/demand/appointment',
					events: {
						// 定义接收事件
						acceptData: (data) => {
							console.log('時間:', data);
							if(  data.data.every(subArr => subArr.length === 0) ){
								that.appointmentStr = '選擇時間'
								that.appointmentList = [[],[],[],[],[],[],[]]
							} else {
								that.appointmentStr = '已選擇'
								that.appointmentList = data.data
							}
						}
					},
					success: (res) => {
						// 向B页面传递初始数据（可选）
						res.eventChannel.emit('initData', { times: that.appointmentList });
					}
				});
			},
			submit(){
				let that = this;
				let data = {};
				
				//數據驗證
				if( that.images.length == 0 ){
					uni.showToast({
						icon:'none',
						title:"封面不能為空"
					})
					return;
				}
				//处理封面 cover:封面图
				let cover = that.images[0].url;
				let img = Object.values(that.images)
					.map(item => item.url)
					.join(',');
					
				//獲取@好友
				let userArr = that.extractMentions(that.form.introduce, '@')
				
				//獲取#話題
				let topicArr = that.extractMentions(that.form.introduce, '#')
					
				let week1 = [], week2 = [], week3 = [], week4 = [], week5 = [], week6 = [], week7 = [];
				for( let i in that.appointmentList[1] ){
					week1.push( that.formatHourToTime(that.appointmentList[1][i]) );
				}
				for( let i in that.appointmentList[2] ){
					week2.push( that.formatHourToTime(that.appointmentList[2][i]) );
				}
				for( let i in that.appointmentList[3] ){
					week3.push( that.formatHourToTime(that.appointmentList[3][i]) );
				}
				for( let i in that.appointmentList[4] ){
					week4.push( that.formatHourToTime(that.appointmentList[4][i]) );
				}
				for( let i in that.appointmentList[5] ){
					week5.push( that.formatHourToTime(that.appointmentList[5][i]) );
				}
				for( let i in that.appointmentList[6] ){
					week6.push( that.formatHourToTime(that.appointmentList[6][i]) );
				}
				for( let i in that.appointmentList[0] ){
					week7.push( that.formatHourToTime(that.appointmentList[0][i]) );
				}
				
				data = {
					channel_id:that.typeItem,//1技能，2召唤，3贴文
					channel_type:that.form.type,
					channel_map:that.form.channel_map,//經緯度
					channel_address:that.form.channel_address,//門店地址
					city_name:that.areaIds,
					description:that.form.introduce,
					cover:cover,
					image:img,
					price:that.price,
					title:that.form.title,
					unitValue:that.unitValue,
					times1:week1,
					times2:week2,
					times3:week3,
					times4:week4,
					times5:week5,
					times6:week6,
					times7:week7,
					tags:topicArr,
					user_tags:userArr,
					channel_category:that.form.classify,
					nums:this.nums //次數/天數單位
				}
				
				archivesPost(data).then((res) => {
					console.log('sucess', res)
					//success
					uni.showToast({
						icon:'none',
						title:"發佈成功"
					})
					setTimeout(()=>{
						uni.switchTab({
							url: '/pages/home/index'
						});
					},1000)
				}).catch((e) =>{
					console.log('error', e)
				})
			},
			formatHourToTime(num){
				if (typeof num !== 'number' || num < 0 || num > 23) {
					console.warn('请输入0-23之间的数字');
				    return '00:00';
				}
				  
				// 补零处理并拼接时间格式
				const hour = num.toString().padStart(2, '0');
				return `${hour}:00`;
			}
		}
	}
</script>

<style lang="scss" scoped>
	.content {
		width: 100%;
		background-color: #F6F8FA;
		min-height: 100vh;
		padding-bottom: 30rpx;
	}
	.list-item{
		display: flex;
		justify-content: space-between;
		box-sizing: border-box;
		padding: 34rpx 24rpx;
		background-color: #FFF;
		margin-top: 2rpx;
		align-items: center;
		
		.list-item-title{
			display: flex;
			justify-content: flex-start;
			align-items: center;
			
			.item-title{
				display: flex;
				justify-content: flex-start;
				align-items: center;
				width: 144rpx;
				font-size: 28rpx;
				
				.title{
					color: #232426;
					font-size: 28rpx;
					font-weight: 500;
				}
				.warning-bag{
					color: #FF3D43;
					margin-left: 10rpx;
				}
			}
			.item-subtitle{
				color: #BEC0C5;
				font-size: 28rpx;
				font-weight: 500;
				margin-left: 24rpx;
				width: 400rpx;
			}
			.item-subtitle-active{
				color: #232426;
				font-size: 28rpx;
				font-weight: 500;
				margin-left: 24rpx;
			}
		}
		
	}
	
	.list-item:first-of-type{
		border-top-left-radius: 24rpx;
		border-top-right-radius: 24rpx;
	}
	.list-item:last-of-type{
		border-bottom-left-radius: 24rpx;
		border-bottom-right-radius: 24rpx;
	}
	.container{
		position: relative;
		width: 100vw;
		height: 100vh;
		box-sizing: border-box;
		
		.imgs{
			position: absolute;
			top: 50%;           /* 顶部定位到父容器 50% 位置 */
			left: 50%;          /* 左侧定位到父容器 50% 位置 */
			transform: translate(-50%, -50%); /* 自身宽高的 -50% 偏移 */
			width: 100%;
			text-align: center;
		}
		
		.footer{
			width: 100%;
			position: absolute;
			display: flex;
			justify-content: space-between;
			padding: 0 50rpx;
			box-sizing: border-box;
			bottom: 50rpx;
			background-color: #232426;
			padding: 20rpx 0;
			
			.btn{
				color: #FFF;
			}
		}
	}
	.user-search-popup{
		width: 100%;
		background-color: #FAFAFA;
		padding: 24rpx 48rpx;
		box-sizing: border-box;
		min-height: 550rpx;
		
		.search-popup-item{
			display: flex;
			justify-content: flex-start;
			align-items: center;
			margin-top: 20rpx;
			
			.title{
				margin-left: 20rpx;
				font-size: 24rpx;
				color:#232426;
			}
			.highlight {
			  color: #27C5D6; /* 红色高亮 */
			  font-weight: bold; /* 可选：加粗强调 */
			}
		}
	}
	.popup-push-type{
		padding: 58rpx 40rpx 28rpx;
		
		.popup-push-header{
			display: flex;
			justify-content: space-between;
			align-items: center;
			
			.site{
				color: #808690;
				font-size: 32rpx;
			}
			.title{
				color: #232426;
				font-size: 30rpx;
				font-weight: 600;
			}
			.btn{
				color: #27C5D6;
				font-size: 32rpx;
			}
		}
		.popup-push-body{
			margin-top: 24rpx;
			
			.popup-push-list{
				
				box-sizing: border-box;
				
				.popup-push-item{
					margin-top: 32rpx;
					padding: 20rpx 48rpx;
					display: flex;
					justify-content: flex-start;
					align-items: center;
					background: #F6F8FA;
					border-radius: 120rpx;
					
					.popup-push-icon{
						
					}
					.popup-push-radio{
						border-radius: 50%;
						width: 48rpx;
						height: 48rpx;
						background-color: #E5E6E8;
					}
					
					.popup-push-text{
						margin-left: 32rpx;
						width: 500rpx;
						
						.title{
							font-size:28rpx;
							font-weight: 600;
						}
						.describe{
							color:#6A707C;
							font-size:24rpx;
							
						}
					}
					
					.popup-push-arrow{
						margin-left: 32rpx;
					}
					
				}
			}
		}
	}
</style>
